package com.hly.musicbackground.model.user.service.impl;

import com.hly.musicbackground.Enum.UserLogEnum;
import com.hly.musicbackground.Utils.MD5Utils;
import com.hly.musicbackground.Utils.RequestContextUtils;
import com.hly.musicbackground.Utils.StringUtils;
import com.hly.musicbackground.domain.User;
import com.hly.musicbackground.exception.BusinessException;
import com.hly.musicbackground.model.auth.service.VerificationMailService;
import com.hly.musicbackground.model.user.params.UpdatePasswordParams;
import com.hly.musicbackground.model.user.service.UserLogService;
import com.hly.musicbackground.model.user.service.UserPasswordService;
import com.hly.musicbackground.model.user.service.UserService;
import com.hly.musicbackground.result.Code;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserPasswordServiceImpl implements UserPasswordService {

    private final VerificationMailService verificationMailService;
    private final UserService userService;
    private final UserLogService userLogService;

    private final MD5Utils md5Utils;

    @Override
    public void updatePassword(UpdatePasswordParams params) {
        User user = null;
        UserLogEnum logEnum = null;
        if (StringUtils.isNotEmpty(params.getSms())){
            verificationMailService.isVerificationMail(params.getMail(), params.getSms());
            user = userService.getUserInfo(params.getMail());
            if (user == null){
                throw new BusinessException(Code.BUSINESS_ERR, "邮箱有误");
            }
            logEnum = UserLogEnum.FIND_PASSWORD;
        }else {
            user = userService.getUserInfo(RequestContextUtils.getUser().getUserId(),
                    params.getOldPassword());
            if (user == null){
                throw new BusinessException(Code.BUSINESS_ERR, "旧密码错误");
            }
            logEnum = UserLogEnum.UPDATE_PASSWORD;
        }

        userLogService.addUserLogOrFail(logEnum);
        user.setPassword(md5Utils.encrypt(params.getPassword()));
        userService.updateById(user);
    }
}
